package edu.yngsxy.wxdemo.core.config;

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 *  全局配置日期时间格式（适用于整个项目）:Jackson 库在将字符串 "2024-12-09 09:52:20" 反序列化为LocalDateTime类型时，无法识别该格式。LocalDateTime默认期望的格式是 ISO 标准格式（如 "2024-12-09T09:52:20"）
 */
@Configuration
public class DateTimeConfig {
    // 序列化格式
    private static final String FORMAT_PATTERN = "yyyy-MM-dd HH:mm:ss";

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            // 配置LocalDateTime的序列化和反序列化格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(FORMAT_PATTERN);
            builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
            builder.deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));
        };
    }
}

